package gpucore

import (
	"fmt"

	"github.com/cogentcore/webgpu/wgpu"
)

// BufferUsage 定义缓冲区用途
type BufferUsage uint32

const (
	BufferUsageStorage BufferUsage = 1 << iota
	BufferUsageUniform
	BufferUsageMapRead
	BufferUsageMapWrite
	BufferUsageCopySrc
	BufferUsageCopyDst
)

func (u BufferUsage) toWGPU() wgpu.BufferUsage {
	var usage wgpu.BufferUsage
	if u&BufferUsageStorage != 0 {
		usage |= wgpu.BufferUsageStorage
	}
	if u&BufferUsageUniform != 0 {
		usage |= wgpu.BufferUsageUniform
	}
	if u&BufferUsageMapRead != 0 {
		usage |= wgpu.BufferUsageMapRead
	}
	if u&BufferUsageMapWrite != 0 {
		usage |= wgpu.BufferUsageMapWrite
	}
	if u&BufferUsageCopySrc != 0 {
		usage |= wgpu.BufferUsageCopySrc
	}
	if u&BufferUsageCopyDst != 0 {
		usage |= wgpu.BufferUsageCopyDst
	}
	return usage
}

// AlignUniform 将任意字节切片对齐到 256 字节（WebGPU uniform 要求）
func AlignUniform(data []byte) []byte {
	const alignment = 256
	size := len(data)
	alignedSize := ((size + alignment - 1) / alignment) * alignment
	padded := make([]byte, alignedSize)
	copy(padded, data)
	return padded
}

// mapStatusToError 转换 WebGPU 异步状态
func mapStatusToError(status wgpu.BufferMapAsyncStatus) error {
	if status == wgpu.BufferMapAsyncStatusSuccess {
		return nil
	}
	return fmt.Errorf(status.String())
}
